package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/samber/do/v2"

	"gitee.com/monkeyPP/happy-mall/pkg/log"
	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/application"
	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/interfaces/api/request"
	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/interfaces/api/response"
)

type ProductHandler interface {
	AddProduct(*gin.Context)
}

type ProductHandlerImpl struct {
	productApp application.ProductApp
}

func NewProductHandler(i do.Injector) (ProductHandler, error) {
	productApp := do.MustInvoke[application.ProductApp](i)
	return &ProductHandlerImpl{
		productApp: productApp,
	}, nil
}

func (h *ProductHandlerImpl) AddProduct(c *gin.Context) {
	var req request.AddProductRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	log.C(c).Infow("add product request", "req", req)

	product, err := h.productApp.AddProduct(c, &req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"product": response.Product{
			ID: product.ID,
		},
	})
}
